<script setup>
import useWeb3 from "../hooks/useWeb3";
import { ref, onMounted, computed } from "vue";
import CryptoJS from "crypto-js";
const { web3, voteContract, getAccount } = useWeb3();

// 看板信息
const board = ref([]);

// 定义开始时间和结束时间
const startTime = ref(0);
const endTime = ref(0);

// 定义当前时间
const currentTime = ref(Math.floor(Date.now() / 1000));

// 定义投票标题
const voteItem = ref("");

const account = ref("");

const getBoardInfo = async () => {
    const result = await voteContract.methods.getBoardInfo().call();
    board.value = result;
};

// 获取投票时间
const getVotingPeriod = async () => {
    try {
        const result = await voteContract.methods.getVotingPeriod().call();
        console.log("getVotingPeriod result:", result); // 调试日志

        // 通过属性名访问返回值
        if (result && result[0] && result[1]) {
            startTime.value = parseInt(result[0]); // 开始时间
            endTime.value = parseInt(result[1]);   // 结束时间
        } else {
            console.error("getVotingPeriod returned unexpected format:", result);
        }
    } catch (error) {
        console.error("Failed to get voting period:", error);
    }
};

// 获取投票标题
const getVoteItem = async () => {
    try {
        const result = await voteContract.methods.getVoteItem().call();
        voteItem.value = result;
    } catch (error) {
        console.error("Failed to get vote item:", error);
    }
};


// 更新当前时间
const updateCurrentTime = () => {
    currentTime.value = Math.floor(Date.now() / 1000);
};

// 计算剩余时间
const remainingTime = computed(() => {
    if (currentTime.value < startTime.value) {
        return `投票尚未开始，距离开始还有：${formatDuration(startTime.value - currentTime.value)}`;
    } else if (currentTime.value >= startTime.value && currentTime.value <= endTime.value) {
        return `剩余时间：${formatDuration(endTime.value - currentTime.value)}`;
    } else if (startTime.value == 0 && endTime.value == 0) {
        return "投票未发起";
    } else
        return "投票已结束";

});

// 格式化时间差
const formatDuration = (duration) => {
    const hours = Math.floor(duration / 3600);
    const minutes = Math.floor((duration % 3600) / 60);
    const seconds = duration % 60;
    return `${hours}小时 ${minutes}分钟 ${seconds}秒`;
};

// 检查是否可以投票
const canVote = computed(() => {
    return currentTime.value >= startTime.value && currentTime.value <= endTime.value;
});

// 判断投票是否结束
const isVoteEnded = computed(() => {
    return currentTime.value > endTime.value && endTime.value !== 0;
});



const secretKey = "my-super-secret-key-1234567890"; // 32 字节的密钥

// 加密函数
const encryptVoteId = (voteId, secretKey) => {
    return CryptoJS.AES.encrypt(voteId.toString(), secretKey).toString();
};

// 解密函数
const decryptVoteId = (encryptedVoteId, secretKey) => {
    const bytes = CryptoJS.AES.decrypt(encryptedVoteId, secretKey);
    return parseInt(bytes.toString(CryptoJS.enc.Utf8)); // 转换为数字
};

//投票
const vote = async (index) => {
    if (!canVote.value) {
        alert("当前时间不允许投票");
        return;
    }

    const secretKey = "my-super-secret-key-1234567890"; // 替换为实际的密钥
    const encryptedIndex = encryptVoteId(index, secretKey); // 加密投票 ID

    const account = await getAccount();
    await voteContract.methods
        .vote(encryptedIndex) // 提交加密后的投票 ID
        .send({ from: account })
        .on("receipt", () => {
            console.log("投票成功！");
        })
        .on("error", (error) => {
            console.error("投票失败:", error);
        });
};



const voteResults = ref([]); // 存储解密后的投票结果

const hasFetchedResults = ref(false); // 标志变量

const getVoteResults = async () => {

    if (hasFetchedResults.value) {
        console.log("投票结果已获取，无需重复调用");
        return;
    }

    const secretKey = "my-super-secret-key-1234567890"; // 替换为实际的密钥

    try {
        // 获取所有投票人的加密投票数据
        const result = await voteContract.methods.getAllVoters().call();
        console.log("getAllVoters result:", result); // 打印返回值

        // 如果返回值是对象，提取 voterAddresses 和 voterList
        const voterAddresses = result[0];
        const voterList = result[1];

        // 解密并统计投票结果
        const voteCounts = {}; // 用于统计每个候选人的票数
        for (let i = 0; i < voterList.length; i++) {
            if (!voterList[i].targetId) {
                // 将投票结果存入 voteResults
                voteResults.value.push({
                    address: voterAddresses[i], // 投票人地址
                    voteIndex: "未投票", // 解密后的投票 ID
                });

                // console.log(`第 ${i + 1} 个用户的 targetId 为空，跳过`);
                continue; // 跳过当前循环
            }
            const decryptedIndex = decryptVoteId(voterList[i].targetId, secretKey);



            // 统计票数
            if (voteCounts[decryptedIndex]) {
                voteCounts[decryptedIndex] += 1;
            } else {
                voteCounts[decryptedIndex] = 1;
            }

            // 将投票结果存入 voteResults
            voteResults.value.push({
                address: voterAddresses[i], // 投票人地址
                voteIndex: decryptedIndex, // 解密后的投票 ID
            });

        }

        // 将统计结果转换为数组
        const indices = [];
        const amounts = [];
        for (const index in voteCounts) {
            indices.push(Number(index));
            amounts.push(voteCounts[index]);
        }

        // 调用智能合约，批量更新票数
        const account = await getAccount();
        await voteContract.methods
            .updateBoardTotalAmounts(indices, amounts)
            .send({ from: account })
            .on("receipt", () => {
                console.log("票数更新成功！");
            })
            .on("error", (error) => {
                console.error("票数更新失败:", error);
            });

        // 重新获取看板信息
        await getBoardInfo();

        // 将投票结果和标志变量存入 localStorage
        localStorage.setItem("voteResults", JSON.stringify(voteResults.value));
        localStorage.setItem("hasFetchedResults", "true");

        // 设置标志变量为 true，表示已经调用过
        hasFetchedResults.value = true;

    } catch (error) {
        console.error("Failed to get vote results:", error);
    }
};



// 初始化事件监听
const initEventListen = () => {
    voteContract.events
        .voteSuccess({ fromBlock: 0 }, (err, event) => {
            console.log("监听执行");
            console.log(event);
        })
        .on("data", (event) => {
            console.log("智能合约触发的事件：", event.returnValues);
        });
};


// onMounted(async () => {
//     await getVotingPeriod();
//     await getBoardInfo();
//     await getVoteItem(); // 获取投票标题
//     initEventListen();
//     setInterval(updateCurrentTime, 1000); // 每秒更新当前时间

//     // // 投票结束后获取投票结果
//     // if (isVoteEnded.value) {
//     //     await getVoteResults();
//     // }
// });



// onMounted(async () => {
//     await getVotingPeriod();
//     await getBoardInfo();
//     await getVoteItem(); // 获取投票标题
//     initEventListen();
//     setInterval(updateCurrentTime, 1000); // 每秒更新当前时间

//     // // 投票结束后获取投票结果
//     // if (isVoteEnded.value && !hasFetchedResults) {
//     //     hasFetchedResults = true; // 设置标志为 true
//     //     await getVoteResults();
//     // }
// });

// onMounted(async () => {
//     await getVotingPeriod();
//     await getBoardInfo();
//     await getVoteItem(); // 获取投票标题
//     initEventListen();
//     setInterval(updateCurrentTime, 1000); // 每秒更新当前时间

//     // 从 localStorage 中读取投票结果
//     const storedResults = localStorage.getItem("voteResults");
//     if (storedResults) {
//         voteResults.value = JSON.parse(storedResults);
//         hasFetchedResults.value = true; // 标记为已获取
//     }
// });

onMounted(async () => {
    await getVotingPeriod();
    await getBoardInfo();
    await getVoteItem(); // 获取投票标题
    initEventListen();
    setInterval(updateCurrentTime, 1000); // 每秒更新当前时间

    // 从 localStorage 中读取 voteResults
    const storedResults = localStorage.getItem("voteResults");
    if (storedResults) {
        voteResults.value = JSON.parse(storedResults);
    }

    // 从 localStorage 中读取 hasFetchedResults
    const fetched = localStorage.getItem("hasFetchedResults");
    if (fetched === "true") {
        hasFetchedResults.value = true;
    }
});

// 格式化时间戳
const formatTime = (timestamp) => {
    if (!timestamp) return "未设置";
    const date = new Date(timestamp * 1000);
    return date.toLocaleString(); // 转换为本地时间格式
};

</script>


<template>
    <div class="box3">
        <van-divider>投票看板</van-divider>

        <!-- 时间信息 -->
        <div class="time-info">
            <div class="time-item">
                <p class="label"><van-icon name="clock-o" />开始时间</p>
                <p class="time">{{ formatTime(startTime) }}</p>
            </div>
            <div class="time-item">
                <p class="label"><van-icon name="clock-o" />结束时间</p>
                <p class="time">{{ formatTime(endTime) }}</p>
            </div>
            <div class="remaining-time">
                <van-divider>{{ remainingTime }}</van-divider>
            </div>
        </div>

        <!-- 投票标题 -->
        <div class="vote-title">
            <p class="title">{{ voteItem || "暂无投票标题" }}</p>
        </div>

        <!-- 投票结果 -->
        <div v-if="isVoteEnded" class="vote-results">
            <h3>投票结果</h3>
            <van-button @click="getVoteResults" :disabled="hasFetchedResults">获取投票结果</van-button>
            <van-cell v-for="(result, index) in voteResults" :key="index" :title="`投票人: ${result.address}`"
                :value="`投票 ID: ${result.voteIndex}`" />
        </div>

        <!-- 候选人列表 -->
        <van-cell :title="item.name" icon="shop-o" v-for="(item, index) in board" :key="index">
            <template #right-icon>
                <!-- 投票结束后显示票数 -->
                <span v-if="isVoteEnded" class="vote-count">
                    {{ item.totalAmount }} 票
                </span>
                <!-- 投票未结束时显示投票按钮 -->
                <van-button v-else :disabled="!canVote" @click="vote(index)">
                    投票
                </van-button>
            </template>
        </van-cell>
    </div>
</template>


<style scoped lang="less">
.box3 {
    padding: 24px;
    background-color: #f9f9f9;
    border-radius: 12px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    max-height: 80vh;
    overflow-y: auto;
}

.vote-title {
    margin-bottom: 24px;
    text-align: center;
    font-size: 24px;
    font-weight: bold;
    color: #333;
    padding: 16px;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.time-info {
    margin-bottom: 24px;
    padding: 16px;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.time-item {
    margin-bottom: 16px;
    display: flex;
    align-items: center;
    padding: 8px;
    background-color: #f5f5f5;
    border-radius: 8px;
}

.label {
    font-weight: bold;
    font-size: 16px;
    color: #333;
    margin-right: 12px;
    display: flex;
    align-items: center;

    .van-icon {
        margin-right: 8px;
        color: #ee742f;
    }
}

.time {
    color: #666;
    font-size: 14px;
}

.van-cell {
    margin-bottom: 12px;
    padding: 16px;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    display: flex;
    align-items: center;
    justify-content: space-between;

    .van-cell__title {
        font-size: 16px;
        font-weight: bold;
        color: #333;
    }
}

.van-button {
    margin-left: 12px;
    border-radius: 8px;
    background-color: #ee742f;
    color: #fff;
    font-weight: bold;
    transition: background-color 0.3s ease;

    &:hover {
        background-color: #d65e1f;
    }

    &:disabled {
        background-color: #ccc;
        cursor: not-allowed;
    }
}

.vote-count {
    font-size: 16px;
    font-weight: bold;
    color: #ee742f;
    margin-left: 12px;
}




/* 自定义滚动条样式 */
.box3::-webkit-scrollbar {
    width: 8px;
}

.box3::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 4px;
}

.box3::-webkit-scrollbar-thumb {
    background: #888;
    border-radius: 4px;
}

.box3::-webkit-scrollbar-thumb:hover {
    background: #555;
}

.remaining-time {
    margin-top: 16px;
    padding: 12px;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    text-align: center;

    .van-divider {
        margin: 0;
        font-size: 28px;
        font-weight: bold;
        color: #e80d0d;
        padding: 8px 0;
        background-color: #f9f9f9;
        border-radius: 8px;
    }
}



.vote-results {
    margin-bottom: 24px;
    padding: 16px;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

    h3 {
        font-size: 18px;
        font-weight: bold;
        color: #333;
        margin-bottom: 16px;
    }

    .van-cell {
        margin-bottom: 12px;
        padding: 16px;
        background-color: #f9f9f9;
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }
}
</style>